<template>
    <div>
        <div class="section-wrap">
            <div class="form-section">
                <div class="form-item form-item-style1">
                    <div class="label-title">
                        <label>姓名</label>
                        <i class="iconfont icon-required"></i>
                    </div>
                    <div>
                        <input type="text"
                               v-model="formData.UserName">
                    </div>
                </div>
                <div class="form-item form-item-style1">
                    <div class="label-title">
                        <label>性别</label>
                    </div>
                    <group>
                        <popup-picker :data="list1"
                                      v-model="Sex"
                                      placeholder="请选择"></popup-picker>
                    </group>
                </div>
                <div class="form-item form-item-style1">
                    <div class="label-title">
                        <label>籍贯</label>
                    </div>
                    <div>
                        <input type="text"
                               v-model="formData.Address">
                    </div>
                </div>
                <div class="form-item form-item-style1">
                    <div class="label-title">
                        <label>民族</label>
                    </div>
                    <div>
                        <input type="text"
                               v-model="formData.Nation">
                    </div>
                </div>
                <div class="form-item form-item-style1">
                    <div class="label-title">
                        <label>身份证</label>
                        <i class="iconfont icon-required"></i>
                    </div>
                    <div>
                        <input type="text"
                               v-model="formData.IdentifyId">
                    </div>
                </div>
                <div class="form-item form-item-style1">
                    <div class="label-title">
                        <label>联系电话 </label>
                        <i class="iconfont icon-required"></i>
                    </div>
                    <div>
                        <input type="text"
                               disabled
                               v-model="formData.TelePhone">
                    </div>
                </div>
                <div class="form-item form-item-style1">
                    <div class="label-title">
                        <label>单位</label>
                    </div>
                    <div>
                        <div class="right-select"
                             @click="selectType">
                            {{$store.state.checkcompany.Name?$store.state.checkcompany.Name:"请选择"}}
                            <i class="iconfont icon-jinru rightmsg"
                               v-if="role==2"></i>
                        </div>
                    </div>
                </div>
                <div class="form-item form-item-style1">
                    <div class="label-title">
                        <label>员工卡号</label>
                    </div>
                    <div>
                        <input type="text"
                               v-model="formData.ReadCardId">
                    </div>
                </div>
                <div class="form-item form-item-style1">
                    <div class="label-title">
                        <label>人员类型</label>
                        <i class="iconfont icon-required"></i>
                    </div>
                    <group>
                        <popup-picker :data="list2"
                                      v-model="Station"
                                      @on-change="selectCategory2"
                                      placeholder="请选择"></popup-picker>
                    </group>
                </div>
                <div class="form-item form-item-style1" v-if="Station[0]=='管理人员'">
                <div class="label-title">
                    <label>岗位</label>
                    <i class="iconfont icon-required"></i>
                </div>
                <group>
                    <popup-picker :data="list3"
                                  v-model="UserKind"
                                  @on-show="selectCategory"
                                  placeholder="请选择"></popup-picker>
                </group>
            </div>
            <div class="form-item form-item-style1" v-if="Station[0]=='施工人员'">
                <div class="label-title">
                    <label>工种</label>
                    <i class="iconfont icon-required"></i>
                </div>
                <group>
                    <popup-picker :data="list3"
                                  v-model="UserKind"
                                  @on-show="selectCategory"
                                  placeholder="请选择"></popup-picker>
                </group>
            </div>
            <div class="form-item form-item-style1" v-if="Station[0]=='施工人员'">
                <group style="width: 100%">
                    <x-switch title="是否为特种作业人员"
                              v-model="formData.IsSpecialOperator"></x-switch>
                </group>
            </div>
            <div class="form-item form-item-style1" v-if="Station[0]=='施工人员'">
                <group style="width: 100%">
                    <x-switch title="是否为特种设备作业人员"
                              v-model="formData.IsSpecialEqmentOperator"></x-switch>
                </group>
            </div>

                <div class="btns">
                    <button @click="submit">提交</button>
                </div>

            </div>
            <div>
                <alert v-model="show"
                       @on-hide="onHide"> {{message}}</alert>
            </div>
        </div>
        <div class="telVerify"
             style="z-index:3;"
             v-if="showTelVerify">
            <div class="bg"></div>
            <div class="content">
                <div class="item">
                    <label>手机号:</label>
                    <div>
                        <input type="text"
                               placeholder="请输入手机号"
                               v-model="tel" />
                    </div>
                </div>
                <div class="item">
                    <label>验证码:</label>
                    <div>
                        <input type="text"
                               placeholder="请输入验证码"
                               v-model="code" />
                        <button :disabled="time !== 60"
                                @click="startTime">{{time == 60?'验证码':`${time}s`}}</button>
                    </div>
                </div>
                <button class="submit"
                        @click="verifyTel">确定</button>
            </div>
        </div>
    </div>
</template>
<script>
import { XSwitch, Group, Cell } from 'vux'
import { categoryList, qrcodeValid, verifyTelByQr, personRegister } from '@/api/api'

export default {
    data () {
        return {
            show: false,
            message: '',
            special1: 0, // 特种作业人员
            special2: 0, // 特种设备祖业人员
            Sex: [],
            Station: [],
            UserKind: [],
            list1: [['男', '女']],
            list2: [['管理人员', '施工人员']],
            list3: [],
            formData: {},
            role: '2',
            categoryData: [],
            departSir: '11',
            isScan: false,
            param: {
                allowPaging: true,
                data: '18379201370',
                pageIndex: 0,
                pageSize: 20
            },
            showTelVerify: false,
            tel: '',
            time: 60,
            code: '',
            setInterval: null
        }
    },
    created () {
        let model = {}
        if (localStorage.getItem('userDetail')) {
            let userMsg = JSON.parse(localStorage.getItem('userDetail'))
            this.Sex = userMsg.Sex || []
            this.Station = userMsg.Station || []
            this.UserKind = []
            this.formData = userMsg.formData
            model = {
                Id: this.$store.state.checkcompany.Id,
                Name: this.$store.state.checkcompany.Name
            }
            this.departSir = this.$store.state.checkcompany.Category
            localStorage.removeItem('userDetail')
        } else if (localStorage.getItem('loginInfo')) {
            let loginInfo = JSON.parse(localStorage.getItem('loginInfo'))
            this.formData = {
                UserName: loginInfo.name || '',
                UserAccount: loginInfo.no || '',
                TelePhone: loginInfo.telephone || '',
                IdentifyId: loginInfo.identity_card || '',
                openid: loginInfo.openid || '',
                unionid: loginInfo.unionid || '',
                Nation: loginInfo.nation || '',
                Sex: loginInfo.sex || '',
                userid: loginInfo.userid || ''
            }
            this.Sex = loginInfo.sex === '1' ? ['男'] : ['女']
        } else {
            model = {
                Id: this.$route.query.departID,
                Name: this.$route.query.departName
            }
        }
        this.$store.state.checkcompany = model
        this.formData.DepartID = this.$store.state.checkcompany.Id
        let endTime = this.$route.query.endTime
        if (endTime) {
            // 扫码进入，校验二维码
            this.isScan = true
            this.departSir = this.$route.query.Category
            qrcodeValid({ data: endTime }).then((res) => {
                if (res.code === 0) {
                    this.show = false
                    this.showTelVerify = true
                } else {
                    this.message = '二维码已失效！'
                    this.show = true
                }
            })
        }
    },
    components: {
        XSwitch,
        Group,
        Cell
    },
    beforeDestroy () {
        clearInterval(this.setInterval)
    },
    methods: {
        onHide () {
            WeixinJSBridge.call('closeWindow')
        },
        selectType () {
            if (!this.isScan) {
                let userMsg = {
                    Sex: this.Sex,
                    Station: this.Station,
                    UserKind: this.UserKind,
                    formData: this.formData
                }
                localStorage.setItem('userDetail', JSON.stringify(userMsg))
                this.$router.push({ path: '/addCompany', query: { telephone: this.formData.TelePhone } })
            }
        },
        selectCategory2 () {
            this.UserKind = []
        },
        selectCategory () {
            this.UserKind = []
            if (!this.formData.DepartID) {
                this.$vux.toast.text('请选择单位')
                this.show = false
                return false
            }
            if (!this.Station || this.Station.length === 0) {
                this.$vux.toast.text('请选择人员类型')
                this.show = false
                return false
            }
            let type = this.Station[0] === '管理人员' ? '0' : '1'
            let param = {
                allowPaging: true,
                data: {
                    type: type,
                    departSir: this.departSir
                },
                pageIndex: 0,
                pageSize: 20
            }
            categoryList(param).then((res) => {
                this.list3 = []
                let data = []
                this.categoryData = res.data
                res.data.forEach(category => {
                    data.push(category.UserType)
                })
                this.list3.push(data)
            })
        },
        startTime () {
            if (this.time !== 60) return false
            if (!(/^1[3456789]\d{9}$/.test(this.tel))) {
                this.$vux.toast.text('请输入正确的手机号')
                return false
            }
            this.getCode()
            this.time--
            this.setInterval = setInterval(() => {
                this.time--
                if (this.time <= 0) {
                    this.time = 60
                    clearInterval(this.setInterval)
                }
            }, 1000)
        },
        getCode () {
            let params = {
                'business': 'SMSverification',
                'data': this.tel
            }
            this.$axiosAjax.getConfigJson(params).then((res) => {
                if (res.data.code == 0) {
                    clearInterval(this.setInterval)
                    this.setInterval = setInterval(() => {
                        this.time--
                        if (this.time <= 0) {
                            this.time = 60
                            clearInterval(this.setInterval)
                        }
                    }, 1000)
                }
            })
        },
        verifyTel () {
            if (!(/^1[3456789]\d{9}$/.test(this.tel))) {
                this.$vux.toast.text('请输入正确的手机号')
                return false
            } else if (!this.code) {
                this.$vux.toast.text('请输入验证码')
                return false
            }
            let params = {
                allowPaging: true,
                data: {
                    tel: this.tel,
                    code: this.code
                },
                pageIndex: 0,
                pageSize: 20
            }
            verifyTelByQr(params).then((res) => {
                if (res.code === 0) {
                    if (res.data) {
                        this.formData.UserName = res.data.name
                        this.formData.UserAccount = res.data.no
                        this.formData.IdentifyId = res.data.identity_card
                        this.formData.openid = res.data.openid
                        this.formData.unionid = res.data.unionid
                        this.formData.Nation = res.data.nation
                        this.formData.Sex = res.data.sex
                        if (res.data.sex) {
                            this.Sex = res.data.sex === '1' ? ['男'] : ['女']
                        } else {
                            this.Sex = []
                        }
                    }
                    this.formData.TelePhone = this.tel
                    this.showTelVerify = false
                }
            }).catch((res) => {
            })
        },
        submit () {
            if (!this.formData.UserName) {
                this.$vux.toast.text('请输入姓名')
                this.show = false
                return false
            }
            if (!(/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(this.formData.IdentifyId))) {
                this.$vux.toast.text('请输入正确的身份证')
                this.show = false
                return false
            }
            if (!(/^1[3456789]\d{9}$/.test(this.formData.TelePhone))) {
                this.$vux.toast.text('请输入正确的手机号')
                this.show = false
                return false
            }
            if (!this.formData.DepartID) {
                this.$vux.toast.text('请选择单位')
                this.show = false
                return false
            }
            if (!this.Station || this.Station.length === 0) {
                this.$vux.toast.text('请选择人员类型')
                this.show = false
                return false
            }
            if (!this.UserKind || this.UserKind.length === 0) {
                this.$vux.toast.text('请选择岗位（工种）')
                this.show = false
                return false
            }
            if (!this.Sex || this.Sex.length !== 0) {
                this.formData.Sex = this.Sex[0] === '男' ? '1' : '2'
            }
            this.formData.Station = this.Station[0]
            this.categoryData.forEach(category => {
                if (category.UserType === this.UserKind[0]) {
                    this.formData.UserKind = category.ID
                }
            })
            personRegister({ data: this.formData }).then((res) => {
                if (res.code == 0) {
                    if (this.isScan) {
                        this.message = '注册成功，请手动点击关闭页面，前往微信小程序！'
                        this.show = true
                    } else {
                        localStorage.setItem('userInfo', JSON.stringify(res))
                        if (this.$route.query.redirect) {
                            this.$router.replace(this.$route.query.redirect)
                        } else {
                            let wechatType = localStorage.getItem('wechatType') || 1
                            wechatType = wechatType == 'undefined' ? 1 : wechatType
                            let redirect
                            if (wechatType == 1) {
                                redirect = '/Index/IndexManager'
                            } else if (wechatType == 2) {
                                redirect = '/rootIndex'
                            } else if (wechatType == 3) {
                                redirect = '/peopleManage2'
                            }
                            this.$router.replace(redirect)
                        }
                    }
                }
            })
        }
    }
}
</script>
<style lang="less" scoped>
.vux-x-switch.weui-cell_switch {
    width: 100%;
}
.right-select {
    font-size: 14px;
    color: #999;
    padding-right: 0px;
    height: 20px;
    overflow: hidden;
    width: 180px;
    position: relative;
    padding-right: 0px;
    line-height: 20px;
    text-align: right;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.icon-jinru {
    color: #c8c8cd;
}
.right-select {
    font-size: 14px;
    color: #999;
}
.lookmsg {
    color: #2269ff;
}
</style>
<style scoped>
.telVerify {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    height: 100%;
}
.bg {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    background: rgba(0, 0, 0, 0.3);
}
.content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    width: 300px;
    padding: 20px;
    background: #fff;
    border-radius: 4px;
}
.content .item {
    color: #666;
    font-size: 16px;
    display: flex;
    padding: 15px 0;
}
.content label {
    width: 60px;
    height: 26px;
    line-height: 26px;
}
.content input {
    width: 100%;
    height: 26px;
    color: #666;
    font-size: 14px;
    border-bottom: 1px solid #ccc;
}
.content .item > div {
    position: relative;
    flex: 1;
}
.content .item button {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 70px;
    height: 30px;
    background: #419df7;
    color: #fff;
    padding: 0 5px;
    border-radius: 2px;
}
.content .item button[disabled] {
    background: #ccc;
}
.submit {
    display: block;
    width: 100%;
    height: 35px;
    margin: 0 auto;
    border-radius: 4px;
    background: #419df7;
    color: #fff;
    margin-top: 10px;
}
</style>
